package com.ruoyi.mobile.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.mobile.domain.*;
import com.ruoyi.mobile.mapper.ISysUserMapper;
import com.ruoyi.mobile.mapper.SchoolPayrecordMapper;
import com.ruoyi.mobile.mapper.SchoolPayrecorddMapper;
import com.ruoyi.mobile.mapper.SchoolStudentMapper;
import com.ruoyi.mobile.service.ISysDeptService;
import com.ruoyi.mobile.service.SchoolClassesService;
import com.ruoyi.mobile.service.SchoolPayrecordService;
import com.ruoyi.mobile.utils.NftResponse;
import com.ruoyi.mobile.utils.Paginator;
import com.ruoyi.mobile.utils.QueryUtil;
import com.ruoyi.mobile.utils.ResponseConstants;
import com.ruoyi.system.api.req.SchoolClassesReq;
import com.ruoyi.system.api.req.SchoolPayrecordReq;
import com.ruoyi.system.api.req.SysDeptReq;
import com.ruoyi.system.api.req.SysUserReq;
import com.ruoyi.system.api.resp.SchoolClassesResp;
import com.ruoyi.system.api.resp.SchoolPayrecordResp;
import com.ruoyi.system.api.resp.SchoolPayrecorddResp;
import com.ruoyi.system.api.resp.SysDeptResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SchoolPayrecordServiceImpl extends ServiceImpl<SchoolPayrecordMapper, SchoolPayrecordEntity> implements SchoolPayrecordService {
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private SchoolClassesService classesService;
    @Autowired
    private ISysUserMapper sysUserMapper;
    @Autowired
    private SchoolPayrecorddMapper schoolPayrecorddMapper;
    @Autowired
    private SchoolStudentMapper schoolStudentMapper;

    @Override
    public NftResponse<Paginator<SchoolPayrecorddResp>> getPayrecordList(SchoolPayrecordReq query) {
        if (query.getPageNo() == null || query.getPageNo() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参页码错误", null);
        }
        if (query.getPageSize() == null || query.getPageSize() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参每页数量错误", null);
        }
        QueryWrapper<SysUserEntity> wrapperUser = new QueryWrapper<>();
        wrapperUser.eq(QueryUtil.camelToUnderline("phonenumber"), query.getPhone());
        wrapperUser.eq(QueryUtil.camelToUnderline("delFlag"),"0");
        wrapperUser.eq(QueryUtil.camelToUnderline("status"), "0");
        List<SysUserEntity> users = sysUserMapper.selectList(wrapperUser);
        List<Long> studentIds = new ArrayList<>();
        for (SysUserEntity user:users) {
            studentIds.add(user.getUserId());
        }
        QueryWrapper<SchoolPayrecorddEntity> wrapperQuery = new QueryWrapper<>();
        wrapperQuery.inSql("school_id", "select dept_id from sys_dept where app_id='"+query.getAppid()+"'");
        wrapperQuery.in(QueryUtil.camelToUnderline("studentId"), studentIds);
        wrapperQuery.orderByDesc("create_time");
        Paginator<SchoolPayrecorddResp> paginator = new Paginator<SchoolPayrecorddResp>(query.getPageNo(), query.getPageSize(), 0, new ArrayList<>());
        Page<SchoolPayrecorddEntity> resultPage = schoolPayrecorddMapper.selectPage(new Page<>(query.getPageNo(), query.getPageSize()), wrapperQuery);
        List<SchoolPayrecorddResp> pageResult = BeanUtil.copyToList(resultPage.getRecords(), SchoolPayrecorddResp.class);
        SysDeptReq queryR = new SysDeptReq();
        queryR.setAppid(query.getAppid());
        SchoolClassesReq queryC = new SchoolClassesReq();
        queryR.setAppid(queryC.getAppid());
        NftResponse<HashMap<Long, SysDeptResp>> schoolMapR = sysDeptService.getSchoolAllMap(queryR);
        NftResponse<HashMap<Long, SchoolClassesResp>> classMapR = classesService.getClassAllMap(queryC);
        HashMap<Long, SysDeptResp> schoolMap = schoolMapR.getData();
        HashMap<Long, SchoolClassesResp> classMap = classMapR.getData();
        for (SchoolPayrecorddResp resp:pageResult) {
            SysDeptResp school = schoolMap.get(resp.getSchoolId());
            resp.setSchoolName(school.getDeptName());
            SysUserReq queryS = new SysUserReq();
            queryS.setSchoolId(resp.getSchoolId());
            queryS.setUserId(resp.getStudentId());
            queryS.setPhone(query.getPhone());
            QueryWrapper<SchoolStudentEntity> wrapperQueryUser = new QueryWrapper<>();
            wrapperQueryUser.eq(QueryUtil.camelToUnderline("studentId"), resp.getStudentId());
            List<SchoolStudentEntity> studentList = schoolStudentMapper.selectList(wrapperQueryUser);
            StringBuffer className = new StringBuffer();
            for (SchoolStudentEntity obj:studentList) {
                className.append(classMap.get(obj.getClassesId()).getClassesName()).append(",");
            }
            String curClassName = className.toString();
            resp.setClassName(curClassName.substring(0,curClassName.lastIndexOf(",")));
        }
        paginator.setPageNo(resultPage.getCurrent());
        paginator.setPageSize(resultPage.getSize());
        paginator.setTotalDataNum(resultPage.getTotal());
        paginator.setPageData(pageResult);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", paginator);
    }

    @Override
    public NftResponse<SchoolPayrecordResp> getPayRemainder(String phone) {
        QueryWrapper<SysUserEntity> wrapperUser = new QueryWrapper<>();
        wrapperUser.eq(QueryUtil.camelToUnderline("phonenumber"), phone);
        wrapperUser.eq(QueryUtil.camelToUnderline("delFlag"),"0");
        wrapperUser.eq(QueryUtil.camelToUnderline("status"), "0");
        List<SysUserEntity> users = sysUserMapper.selectList(wrapperUser);
        List<Long> studentIds = new ArrayList<>();
        for (SysUserEntity user:users) {
            studentIds.add(user.getUserId());
        }
        SchoolPayrecordResp rtn = this.baseMapper.getUserRemainder(studentIds);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", BeanUtil.copyProperties(rtn, SchoolPayrecordResp.class));
    }

    @Override
    @Transactional
    public NftResponse<Boolean> delPayById(Long id) {
        SchoolPayrecordEntity entity = this.baseMapper.selectById(id);
        if (null!=entity) {
            QueryWrapper<SchoolPayrecorddEntity> wrapper = new QueryWrapper<>();
            wrapper.eq(QueryUtil.camelToUnderline("schoolId"), entity.getSchoolId());
            wrapper.eq(QueryUtil.camelToUnderline("studentId"), entity.getStudentId());
            wrapper.eq(QueryUtil.camelToUnderline("createTime"), entity.getCreateTime());
            List<SchoolPayrecorddEntity> list = schoolPayrecorddMapper.selectList(wrapper);
            List<Long> idList = list.stream().map(o->o.getId()).collect(Collectors.toList());;
            schoolPayrecorddMapper.deleteBatchIds(idList);
        }
        int rtn = this.baseMapper.deleteById(id);
        if (rtn>0) {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "删除成功", true);
        }else {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "删除失败", false);
        }
    }
}
